# 版本API
from django.http import JsonResponse
from django import forms
from web.models import Version, Version_Type, VersionImage, Users
from django.forms.models import model_to_dict
from web.apis import tools
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

# 版本表单
class VersionForm(forms.ModelForm):
    class Meta:
        model = Version
        fields = ['version_number', 'version_description', 'version_download_url', 'version_publisher', 'version_status']

# 创建版本
@csrf_exempt
def create_version(request):
    if request.method == 'POST':
        form = VersionForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                version = form.instance
                version_dict = model_to_dict(version)
                version_dict['version_publisher'] = version.version_publisher.username
                version_dict['version_status'] = version.get_version_status_display()
                version_dict['create_time'] = version.create_time.strftime('%Y-%m-%d %H:%M:%S')
                version_dict['update_time'] = version.update_time.strftime('%Y-%m-%d %H:%M:%S')
                return JsonResponse(tools.ReturnData(code=200, msg="版本创建成功", data=version_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'保存版本失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f'{error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg="请使用POST方法"))

# 获取版本列表
@csrf_exempt
def get_version_list(request):
    if request.method == 'GET':
        try:
            versions = Version.objects.all().order_by('-create_time')
            version_list = []
            for v in versions:
                v_dict = model_to_dict(v)
                v_dict['version_publisher'] = v.version_publisher.username if v.version_publisher else ''
                v_dict['version_status'] = v.get_version_status_display() if hasattr(v, 'get_version_status_display') else ''
                v_dict['create_time'] = v.create_time.strftime('%Y-%m-%d %H:%M:%S')
                v_dict['update_time'] = v.update_time.strftime('%Y-%m-%d %H:%M:%S')
                version_list.append(v_dict)
            return JsonResponse(tools.ReturnData(code=200, msg='获取版本列表成功', data=version_list))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取版本列表失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用GET方法'))

# 获取单个版本
@csrf_exempt
def get_version(request, version_id):
    if request.method == 'GET':
        try:
            v = Version.objects.filter(version_id=version_id).first()
            if not v:
                return JsonResponse(tools.ReturnData(code=400, msg='版本不存在'))
            v_dict = model_to_dict(v)
            v_dict['version_publisher'] = v.version_publisher.username if v.version_publisher else ''
            v_dict['version_status'] = v.get_version_status_display() if hasattr(v, 'get_version_status_display') else ''
            v_dict['create_time'] = v.create_time.strftime('%Y-%m-%d %H:%M:%S')
            v_dict['version_type'] = []
            for t in Version_Type.objects.filter(version=v.version_id):
                v_dict['version_type'].append({
                    'version_update_type': t.get_version_update_type_display(),
                    'version_update_description': t.version_update_description
                })
            v_dict['version_image'] = []
            for i in VersionImage.objects.filter(version=v.version_id):
                v_dict['version_image'].append({
                    'image': i.image.url,
                    'create_time': i.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'update_time': i.update_time.strftime('%Y-%m-%d %H:%M:%S')
                })
            v_dict['update_time'] = v.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='获取版本成功', data=v_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'获取版本失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用GET方法'))

# 更新版本
@csrf_exempt
def update_version(request, version_id):
    if request.method == 'POST':
        try:
            v = Version.objects.filter(version_id=version_id).first()
            if not v:
                return JsonResponse(tools.ReturnData(code=400, msg='版本不存在'))
            v.version_number = request.POST.get('version_number', v.version_number)
            v.version_description = request.POST.get('version_description', v.version_description)
            v.version_download_url = request.POST.get('version_download_url', v.version_download_url)
            # version_publisher 通常不更新
            v.update_time = datetime.now()
            # 版本状态
            v.version_status = int(request.POST.get('version_status', v.version_status))
            v.save()
            v_dict = model_to_dict(v)
            v_dict['version_publisher'] = v.version_publisher.username if v.version_publisher else ''
            v_dict['version_status'] = v.get_version_status_display()
            v_dict['create_time'] = v.create_time.strftime('%Y-%m-%d %H:%M:%S')
            v_dict['update_time'] = v.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='更新版本成功', data=v_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'更新版本失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg='请使用POST方法'))

# 删除版本
@csrf_exempt
def delete_version(request, version_id):
    if request.method == 'DELETE':
        try:
            v = Version.objects.filter(version_id=version_id).first()
            if not v:
                return JsonResponse(tools.ReturnData(code=400, msg='版本不存在'))
            v.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除版本成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除版本失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# VersionType表单
class VersionTypeForm(forms.ModelForm):
    class Meta:
        model = Version_Type
        fields = ['version', 'version_update_description', 'version_update_type']

# 创建版本类型
@csrf_exempt
def create_version_type(request):
    if request.method == 'POST':
        form = VersionTypeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                detail = form.instance
                detail_dict = model_to_dict(detail)
                detail_dict['version_update_type'] = detail.get_version_update_type_display()
                return JsonResponse(tools.ReturnData(code=200, msg="版本类型创建成功", data=detail_dict))
            except Exception as e:
                return JsonResponse(tools.ReturnData(code=400, msg=f'保存版本类型失败: {str(e)}'))
        else:
            error_msg = tools.get_first_error(form)
            return JsonResponse(tools.ReturnData(code=400, msg=f'{error_msg}'))
    else:
        return JsonResponse(tools.ReturnData(code=405, msg="请使用POST方法"))

# 删除版本类型
@csrf_exempt
def delete_version_type(request, version_type_id):
    if request.method == 'DELETE':
        try:
            d = Version_Type.objects.filter(id=version_type_id).first()
            if not d:
                return JsonResponse(tools.ReturnData(code=400, msg='版本类型不存在'))
            d.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除版本类型成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除版本类型失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))

# 上传版本图片
@csrf_exempt
def upload_version_image(request, version_id):
    if request.method == 'POST':
        try:
            version = Version.objects.filter(version_id=version_id).first()
            if not version:
                return JsonResponse(tools.ReturnData(code=400, msg='版本不存在'))
            if 'image' not in request.FILES:
                return JsonResponse(tools.ReturnData(code=400, msg='请上传图片'))
            image_file = request.FILES['image']
            version_image = VersionImage.objects.create(version=version, image=image_file)
            image_dict = model_to_dict(version_image)
            image_dict['image'] = version_image.image.url
            image_dict['create_time'] = version_image.create_time.strftime('%Y-%m-%d %H:%M:%S')
            image_dict['update_time'] = version_image.update_time.strftime('%Y-%m-%d %H:%M:%S')
            return JsonResponse(tools.ReturnData(code=200, msg='上传版本图片成功', data=image_dict))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'上传版本图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用POST方法'))

# 删除版本图片
@csrf_exempt
def delete_version_image(request, image_id):
    if request.method == 'DELETE':
        try:
            image = VersionImage.objects.filter(id=image_id).first()
            if not image:
                return JsonResponse(tools.ReturnData(code=400, msg='版本图片不存在'))
            image.delete()
            return JsonResponse(tools.ReturnData(code=200, msg='删除版本图片成功'))
        except Exception as e:
            return JsonResponse(tools.ReturnData(code=400, msg=f'删除版本图片失败: {str(e)}'))
    else:
        return JsonResponse(tools.ReturnData(code=400, msg='请使用DELETE方法'))
